package cn.javadog.algorithm.e1_100;


import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

/**
 * 有效的括号
 * https://leetcode-cn.com/problems/valid-parentheses/
 * @author Sprite
 */
public class Algorithm20 {
	public static void main(String[] args) {
		System.out.println(isValid("()"));
		System.out.println(isValid("()[]{}"));
		System.out.println(isValid("(]"));
		System.out.println(isValid("([)]"));
		System.out.println(isValid("{[]}"));
		System.out.println(isValid("(("));
	}


	public static boolean isValid(String s) {
		if (s.length() == 0) return true;
		if (s.length() % 2 != 0) return false;
		char[] chars = s.toCharArray();
		Map<Character,Character> map = new HashMap<>();
		map.put('(',')');
		map.put('[',']');
		map.put('{','}');
		Set<Character> keySet = map.keySet();

		LinkedList<Character> queue = new LinkedList<>();
		for (int i = 0; i < chars.length; i++) {
			char c = chars[i];
			if (queue.size() > chars.length-i){
				return false;
			}
			if (!queue.isEmpty()){
				Character poll = queue.pollLast();
				if (!map.getOrDefault(poll,'|').equals(c)){
					if (keySet.contains(c)){
						queue.add(poll);
						queue.add(c);
					}else if (!keySet.contains(c)){
						return false;
					}
				}
			}else if (keySet.contains(c)){
				queue.add(c);
			}else {
				return false;
			}
		}
		return queue.isEmpty();
	}
}
